<%@ page contentType="text/html;charset=UTF-8"%>
<script type="text/javascript">
	var _roleTableList,_userId;
	var _isServerPage = true;//是否服务器端分页
	var _tableCols = [ {
		data : "uuid",
		orderable : false,
		className : "center",
		width : "30",
		render : RapDataTableUtils.renderCheckCol
	}, {
		data : 'loginName',
		width : "60",
		orderable : true
	}, {
		data : 'userName',
		width : "80",
		orderable : true
	},
	{
		data : 'groupOneCodes',
		width : "120",
		render : function (data, type, full){
			return RapDataUtils.getEnumNames("stwy_groupOne",data);
		},
		orderable : true
	},
	{
		data : 'groupTwoCodes',
		width : "80",
		render : function (data, type, full){
			return RapDataUtils.getEnumNames("stwy_groupTwo",data);
		},
		orderable : true
	},

/* 	{
		data : 'lastLoginIP',
		width : "80",
		//render : function(){},
		orderable : true
	}, */ 
	{
		data : 'lastLoginTime',
		width : "80",
		orderable : true
	},
	{
		data : "uuid",
		className : "center",
		orderable : false,
		render : RapDataTableUtils.renderActionCol,
		width : "80"
	} ];
	
	function onViewDetailRow(data, rowidx,row) {
		_detailRecord = data;
		_detailRecordIdx = rowidx;
		_row = row;
		_rapui.setDetailMode();
		showData(data);
		showRoleList(data);
	}
	function onAdd() {
		RapFormUtils.clearForm('rap-form-edit');
		$("select[name='status']").val("1");
		_rapui.setEditMode();
		hideRoleList();
	}
	function onEditRow(data) {
		_rapui.setEditMode();
		showData(data);
		showRoleList(data);
	}
	//返回列表视图
	function onBackToList() {
		_rapui.setListMode();
		hideRoleList();
	}
	//取消编辑，返回列表视图
	function onCancel() {
		_validator.resetForm();
		$('#rap-form-edit div.control-group').removeClass('error');
		_rapui.setListMode();
		hideRoleList();
	}
	//保存，isClose 是否保存后关闭视图，否为继续增加状态
	function onSave(isClose) {
		setSelectedGroupText();
		var flag = true;
		if (!$('#rap-form-edit').valid())
			flag = false;
		if(!checkRepeat($('#rap-form-edit input[name="loginName"]'))){
			flag = false;
		}
		if(flag==false){
			return false;
		}
		RapFormUtils.setCheckBoxNotCheckedValue('rap-form-edit');
		var posturl = "${serviceurl}/add";
		var pk = $("input[name='uuid']").val();
		var isAdd = true;
		if (pk != ""){
			posturl = "${serviceurl}/update";
			isAdd = false;
		}
		var opt = {
			url : posturl,
			type : "post",
			success : function(data) {
				if(data.success){
					onRefresh();
					if (isClose) {
						if(isAdd){
							onEditRow(data.records[0]);
						}else{
							_rapui.setListMode();
							hideRoleList();
						}
						
					} else {
						onAdd();
					}
				}
				else{
					alert("保存出现错误：" + data.msg)
				}
			}
		}
		$("#rap-form-edit").ajaxSubmit(opt);
	}
	
	function showRoleList(data){
		_userId = data.uuid;
		loadRoleList();
		$("#rap-page-area-role").removeClass("hide");
	}
	function hideRoleList(){
		$("#rap-page-area-role").addClass("hide");
	}
	function loadRoleList() {
		
		$.ajax({
			url : '${ctx}/modules/sys/userrole/query',
			data : {"search_EQ_user.uuid":_userId},
			dataType : 'json',
			success : function(data) {
				_roleTableList.clear();
				_roleTableList.rows.add(data.records);
				_roleTableList.draw();
			}
		});
	}
	function showData(data) {
		$("input[name='uuid']").val(data.uuid);
		if (data.staff) {
			$("input[name='staff.uuid']").val(data.staff.uuid);
			$("input[name='staffName']").val(data.staff.staffName);
		} else {
			$("input[name='staff.uuid']").val("");
			$("input[name='staffName']").val("");
		}
		$("select[name='status']").val(data.status);
		$("input[name='loginName']").val(data.loginName);
		$("input[name='portrait']").val(data.portrait);
		$("input[name='userName']").val(data.userName);
		$("select[name='userType']").val(data.userType);
		$("input[name='pwdPolicy']").val(data.pwdPolicy);
		$("input[name='showOrder']").val(data.showOrder);
		$("input[name='validDate']").val(data.validDate);
		$("textarea[name='description']").val(data.description);
		$("input[name='invalidDate']").val(data.invalidDate);
		$("input[name='lastLoginIP']").val(data.lastLoginIP);
		$("input[name='lastLoginTime']").val(data.lastLoginTime);
		$("input[name='personId']").val(data.personId);
		$("input[name='personName']").val(data.personName);
		$("input[name='orgId']").val(data.orgId);
		$("input[name='orgName']").val(data.orgName);
		$("input[name='deptId']").val(data.deptId);
		$("input[name='deptName']").val(data.deptName);
		$("input[name='serialNumber']").val(data.serialNumber);
		$("[name='groupOneCodes']").val(data.groupOneCodes);
		$("[name='groupOneNames']").val(data.groupOneNames);
		$("[name='groupTwoCodes']").val(data.groupTwoCodes);
		$("[name='groupTwoNames']").val(data.groupTwoNames);
		setSelected($("select[name='groupOneCodes']"),data.groupOneCodes);
		setSelected($("select[name='groupTwoCodes']"),data.groupTwoCodes);
	}
	function setSelected(obj,values){
		if(values!=null&&values!=''){
			var ids = values.split(",");
			$(obj).val(ids);
		}
	}
	function onResetPwd() {
		var pks = RapDataTableUtils.getSelectPks();
		if (pks == "") {
			alert("请选择需要重置的用户");
			return;
		}
		if (!window.confirm("确实要重置所选择的用户密码吗？")) {
			return;
		}
		$.ajax({
			type : 'post',
			url : '${serviceurl}/resetpwd',
			dataType : 'json',
			data : {
				"pks" : pks.toString()
			},
			success : function(data) {
				if (data.success) {
					alert("密码重置成功");
				} else {
					alert("密码重置失败，原因：" + data.msg);
				}
			}
		});
	}
	//分配用户角色
	function onAssignRole() {
		var pks = RapDataTableUtils.getSelectPks();
		if (pks == "") {
			alert("请选择需要分配角色的用户");
			return false;
		}
		_assignPks = pks;
		$("#rap-btn-assign-role").colorbox({
			iframe : true,
			href : "${ctx}/modules/sys/role/select",
			innerWidth : '90%',
			innerHeight : 450,
			fixed : true
		});
	}
	// 选择关联人员
	function callBackSelectPerson(data) {
		$("input[name='personId']").val(data.uuid);
		$("input[name='personName']").val(data.name);
	}
	// 选择关联机构 
	function callBackSelectOrg(data) {
		$("input[name='orgId']").val(data.id);
		$("input[name='orgName']").val(data.name);
		clearDeptInfo();
		clearPersonInfo();
	}
	function callbackOrgForSearch(data) {
		$("input[name='search_EQ_orgId']").val(data.id);
		$("input[name='search_orgName']").val(data.name);
	}
	
	// 选择部门
	function callBackSelectDept(data) {
		$("input[name='deptId']").val(data.uuid);
		$("input[name='deptName']").val(data.deptName);
		clearPersonInfo();
	}
	function clearDeptInfo(){
		$("input[name='deptId']").val("");
		$("input[name='deptName']").val("");
	}
	function clearPersonInfo(){
		$("input[name='personId']").val("");
		$("input[name='personName']").val("");
	}
	//工具栏复制动作，可批量
	function onCopy() {
		var pks = RapDataTableUtils.getSelectPks();
		RapDataUtils.copyRecord("${serviceurl}/copy", pks, onRefresh);
	}
	function selectPerson(){
		$("#rap-btn-ref-staff").click();
	}
	function selectOrg(){
		$("#rap-btn-ref-org").click();
	}
	function selectDept(){
		$("#rap-btn-ref-dept").click();
	}
	var _roleTableCols =[ {
		orderable : false,
		className : "center",
		width : "30",
		data : "uuid",
		render : RapDataTableUtils.renderCheckCol
	}, {
		data : 'role.rolegroup.rolegroupName',
		width : "100"
	}, {
		data : 'role.roleCode',
		width : "80"
	}, {
		data : 'role.roleName',
		width : "100"
	}, {
		data : 'role.status',
		render : RapDataTableUtils.renderStatusCol,
		width : "50"
	}, {
		dataProp : "uuid",
		className : "center",
		orderable : false,
		render : renderRoleActionCol,
		width : "50"
	} ];
	function renderRoleActionCol(){
		return "<div class='rap-btn-actiongroup'>" 
		+ "<button id='rap-btn-remove-row' class='btn btn-xs btn-danger' data-rel='tooltip' title='删除'><i class='fa fa-trash-o'></i></button>"
		+ "</div>";
	}
	function setRoleActions(nRow, aData, iDataIndex) {
		$('#rap-btn-remove-row', nRow).click(function() {
			removeUserRole(aData, iDataIndex, nRow);
		});
	
	}
	function removeUserRole(aData, rowidx, nRow){
		RapDataUtils.removeRecord('${ctx}/modules/sys/userrole/delete', [ aData.uuid ],
				function() {
					_roleTableList.row(nRow).remove().draw(false);
				});
	}
	function onRemoveUserRole(){
		var pks = RapDataTableUtils.getSelectPks("rap-table-list-role");
		var url = '${ctx}/modules/sys/userrole/delete';
		RapDataUtils.removeRecord(url, pks, loadRoleList);
		
	}
	function onAssignRoleEdit(){
		_assignPks = _userId;
		$("#rap-btn-edit-assign-role").colorbox({
			iframe : true,
			href : "${ctx}/modules/sys/role/select",
			innerWidth : '90%',
			innerHeight : 450,
			fixed : true
		});
	}
	function assignRoleCallback(){
		if(_assignPks == _userId){
			loadRoleList();
		}
	}
	function onSelectDept(){
		$("#rap-btn-ref-dept").colorbox({
			iframe : true,
			opacity	: 0.2,
			transition : 'none',
			speed : 200,
			href : "${ctx}/ent/department/select?entId="+$('#orgId').val(),
			innerWidth : '70%',
			innerHeight : '80%',
			close : '×',
			fixed : true
		});
	}
	function onSelectPerson(){
		$("#rap-btn-ref-staff").colorbox({
			iframe : true,
			opacity	: 0.2,
			href : "${ctx}/ent/member/select?entId="+$('#orgId').val()+"&deptId="+$('#deptId').val(),
			innerWidth : '70%',
			innerHeight : '80%',
			close : '×',
			fixed : true
		});
	}
	/* function popModal(textArea,groupType){
		var opt = {
				content:"<form id='popForm' class='form-inline'>"
					+"<select multiple='multiple' id='group' class='rap-input-enumdata' data-enum-group='"+groupType+"'>"
					+"<button id='closePop' type='button' class='btn btn-xs default btn-pop'><i class='fa fa-times'></i></button>"
					+"<button id='saveNode' type='button' class='btn btn-xs blue btn-pop'><i class='fa fa-check'></i></button>"
					+"</form>",
				html:true,
				trigger:"manual",
				placement:"top"
			};
		$(textArea).popover('destroy');
		$(textArea).popover(opt);
		$(textArea).popover('show');
		_rapui.setUIStyle();
		
		$("#saveNode").bind("click",function(){
			var value = $("#popForm select").val();
			var text = $("#popForm select").text();
			textArea.value = text;
			$(textArea).closest("input[type='hidden']").val(value);
		});
		$("#closePop").bind("click",function(){
			$(textArea).popover('destroy');
		});
	}
	 */
	 function getSelectedText(multiSelect){
		 var options = multiSelect.options;
		 var text = "";
		 for(var i = 0;i<options.length;i++){
			 if(options[i].selected==true){
				 var str = options[i].innerHTML;
				 if(options[i].value!=null&&options[i].value!=""){
					 if(text==""){
						 text =  str;
					 }else{
						 text = text+","+str;
					 }
				 }
			 }
		 }
		 return text;
	 }
	 function setSelectedGroupText(){
		 var dom1 =  $('#groupOne')[0];
		 $('#rap-form-edit input[name="groupOneNames"]').val(getSelectedText(dom1));
		 
		 var dom2 =  $('#groupTwo')[0];
		 $('#rap-form-edit input[name="groupTwoNames"]').val(getSelectedText(dom2));
	 }
	$(document).ready(function() {
		$('#rap-btn-resetpwd').bind('click', onResetPwd);
		$('#rap-btn-assign-role').bind('click', onAssignRole);
		$('#rap-btn-copy').bind('click', onCopy);
		$('#personName').bind('focus', selectPerson);
		$('#deptName').bind('focus', selectDept);
		$('#orgName').bind('focus', selectOrg);
		$('#rap-btn-edit-assign-role').bind('click', onAssignRoleEdit);
		$('#rap-btn-remove-role').bind('click', onRemoveUserRole);
		$('#rap-btn-ref-dept').bind('click', onSelectDept);
		$('#rap-btn-ref-staff').bind('click', onSelectPerson);
		$('#rap-form-edit input[name="loginName"]').bind('blur',function(){
			checkRepeat($(this));
		});
		bindDefaultActions();
		if(_isServerPage){
			//服务器分页
			serverPage();	
		}else{
			//非服务器分页
			_tableList = $('#rap-table-list').DataTable({
				"columns" : _tableCols,
				"createdRow" : RapDataTableUtils.setActions,
				"order": [] 
			});
			loadList();		
		}
		RapDataTableUtils.setCheckCol(_tableList);

		_validator = $('#rap-form-edit').validate({
			rules : {
				userName : {
					required : true
				},
				loginName : {
					required : true,
					isRightfulString : true
				},
				invalidDate : {
					notLessThanDate : "#validDate"
				},
				validDate : {
					required : true
				},
				status : {
					required : true
				},
				showOrder : {
					digits : true
				}
			},
			messages : {
				userName : "请输入用户名",
				loginName : {
					required : "请输入登录名",
					isRightfulString : "含有非法字符"
				},
				invalidDate : {
					
					notLessThanDate : "失效日期不能小于生效日期"
				},
				validDate : "生效日期不能为空",
				status : "请选择状态",
				showOrder : "请输入数字"
			}
		});
		
		$("#rap-btn-ref-org").colorbox({
			iframe : true,
			opacity	: 0.2,
			transition : 'none',
			speed : 200,
			href : "${ctx}/ent/profile/enterprise/select?rootSelectable=true&isPermission=false",
			innerWidth : '300px',
			innerHeight : '80%',
			close : '×',
			fixed : true
		});
		
		$("#rap-btn-ref-org-search").colorbox({
			iframe : true,
			opacity	: 0.2,
			transition : 'none',
			speed : 200,
			href : "${ctx}/ent/profile/enterprise/select?rootSelectable=true&isPermission=false&callback=callbackOrgForSearch",
			innerWidth : '300px',
			innerHeight : '80%',
			close : '×',
			fixed : true
		});
		$('#search_orgName').bind('focus', function(){
			$("#rap-btn-ref-org-search").click();
		});
		
		_roleTableList = $('#rap-table-list-role').DataTable({
			"columns" : _roleTableCols,
			"createdRow" : setRoleActions,
			"order": []
		});
		RapDataTableUtils.setCheckCol(_roleTableList);
	});
	
</script>
